package com.example.test_witns.adapter.friends;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.test_witns.R;
import com.example.test_witns.pojo.Contacts_info;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FriendsAdapter extends RecyclerView.Adapter<FriendsAdapter.FriendsViewHolder>{

    private List<Contacts_info> contactsInfoList;
    private OnFriendsClickListener onFriendsClickListener;

    public interface OnFriendsClickListener{
        void onFriendClicked(byte[] targetAvatar, String userId, String targetNickname);
    }

    public void setOnFriendsClickListener(OnFriendsClickListener onFriendsClickListener){
        this.onFriendsClickListener = onFriendsClickListener;
    }

    public FriendsAdapter(List<Contacts_info> contactsInfoList){ this.contactsInfoList = contactsInfoList; }

    /**
     * @param parent   The ViewGroup into which the new View will be added after it is bound to
     *                 an adapter position.
     * @param viewType The view type of the new View.
     * @return
     */
    @NonNull
    @Override
    public FriendsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contact, parent, false);
        return new FriendsViewHolder(view, onFriendsClickListener);
    }

    /**
     * @param holder   The ViewHolder which should be updated to represent the contents of the
     *                 item at the given position in the data set.
     * @param position The position of the item within the adapter's data set.
     */
    @Override
    public void onBindViewHolder(@NonNull FriendsViewHolder holder, int position) {
        Contacts_info contactsInfo = contactsInfoList.get(position);
        holder.user_Or_Group_NameTextView.setText(contactsInfo.getRemark());
        holder.unreadCountTextView.setText(Long.toString(contactsInfo.getUnreadCount()));
        Bitmap bitmap = null;
        if (contactsInfo.getAvatar() != null) {
            bitmap = BitmapFactory.decodeByteArray(contactsInfo.getAvatar(), 0, contactsInfo.getAvatar().length);
        }else if(contactsInfo.getAvatar_URL() != null){

            String avatarUrl = contactsInfo.getAvatar_URL();

            Glide.with(holder.itemView.getContext())
                    .load(avatarUrl)
                    .into(holder.friendAvatar);
        }else{
            Toast.makeText(holder.itemView.getContext(), "加载失败", Toast.LENGTH_SHORT).show();
        }
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String targetUserId = contactsInfo.getUserId();
                String targetNickname = holder.user_Or_Group_NameTextView.getText().toString();
                byte[] targetAvatar = new byte[0];
                Bitmap bitmap1 = null;
                if(holder.friendAvatar.getDrawable() instanceof BitmapDrawable){
                    bitmap1 = ((BitmapDrawable)holder.friendAvatar.getDrawable()).getBitmap();
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                    targetAvatar = outputStream.toByteArray();
                }
                int position = holder.getBindingAdapterPosition();
                if (position != RecyclerView.NO_POSITION){
                    onFriendsClickListener.onFriendClicked(targetAvatar, targetUserId, targetNickname);
                }
            }
        });
        if (contactsInfo.getUnreadCount() == 0){
            holder.unreadCountTextView.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * @return
     */
    @Override
    public int getItemCount() {
        return contactsInfoList.size();
    }

    public static class FriendsViewHolder extends RecyclerView.ViewHolder {
        public TextView user_Or_Group_NameTextView;
        public TextView last_MassageTextView;
        public TextView last_Contact_TimestampTextView;
        public TextView unreadCountTextView;
        public CircleImageView friendAvatar;

        public FriendsViewHolder(View itemView, final OnFriendsClickListener onFriendsClickListener) {
            super(itemView);
            user_Or_Group_NameTextView = itemView.findViewById(R.id.name);
            unreadCountTextView = itemView.findViewById(R.id.unreadCounter);
            friendAvatar = itemView.findViewById(R.id.contact_avatar);
        }
    }

    public void addFriend(Contacts_info contactsInfo) {
        contactsInfoList.add(contactsInfo);
        notifyItemInserted(contactsInfoList.size() - 1);
    }

    public byte[] downloadAvatar(String avatarUrl) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(avatarUrl)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().bytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void removeAllFriends() {
        contactsInfoList.clear();
        notifyDataSetChanged();
    }
}

//            ExecutorService executor = Executors.newSingleThreadExecutor();
//            executor.execute(new Runnable() {
//                @Override
//                public void run() {
//
//
//                    byte[] avatarBytes = downloadAvatar(contactsInfo.getAvatar_URI());
//                    // 在主线程中更新UI
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (avatarBytes != null) {
//                                Bitmap bitmap;
//                                bitmap = BitmapFactory.decodeByteArray(avatarBytes, 0, avatarBytes.length);
//                                holder.friendAvatar.setImageBitmap(bitmap);
//                            }
//                        }
//                    });
//                }
//            });
